//参考借鉴：https://www.cnblogs.com/bllx/p/9850577.html
//FullCalendar 日历插件中文说明文档：https://blog.csdn.net/ymnets/article/details/78661247
jQuery(function($) {

	/* initialize the external events ---------------------------------------------------------*/

	$('#external-events div.external-event').each(function() {

		// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
		// it doesn't need to have a start or end
		var eventObject = {
			title: $.trim($(this).text()) // use the element's text as the event title
		};

		// store the Event Object in the DOM element so we can get to it later
		$(this).data('eventObject', eventObject);

		// make the event draggable using jQuery UI
		$(this).draggable({
			zIndex: 999,
			revert: true,      // will cause the event to go back to its
			revertDuration: 0  //  original position after the drag
		});
		
	});


	/* 初始化日历 -----------------------------------------------------------------*/

	var date = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();

	var calendar = $('#calendar').fullCalendar({
		//isRTL: true, // 设置为ture时则日历从右往左显示，貌似是针对阿拉伯人设计的。
		firstDay: 1, // 设置一周中显示的第一天是哪天，周日是0，周一是1，类推。 
		buttonHtml: {
			prev: '<i class="ace-icon fa fa-chevron-left"></i>',
			next: '<i class="ace-icon fa fa-chevron-right"></i>'
		},
		nowIndicator : true, //周/日视图中显示今天当前时间点（以红线标记），默认false不显示
		weekNumbers:true,//显示周数
		weekNumberTitle : "周数",  
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		events: [
			{
			title: '全天的事件',
			start: new Date(y, m, 1),
			className: 'label-important'
		  },
		  {
			title: '长事件',
			start: moment().subtract(5, 'days').format('YYYY-MM-DD'),
			end: moment().subtract(1, 'days').format('YYYY-MM-DD'),
			className: 'label-success'
		  },
		  {
			title: '一些事件',
			start: new Date(y, m, d-3, 16, 0),
			allDay: false,
			className: 'label-info'
		  }
		],
		eventResize: function(event, delta, revertFunc) {
			console.log(event);
//			alert(event.title + " end is now " + event.end.format());
//			if (!confirm("is this okay?")) {
//				revertFunc();
//			}
			bootbox.confirm({
				message: "确定要修改【id:" + event._id + ",title:" + event.title + "】的时间吗?",
				buttons: {
				  confirm: {
					 label: "确定",
					 className: "btn-primary btn-sm",
				  },
				  cancel: {
					 label: "取消",
					 className: "btn-sm",
				  }
				},
				callback: function(result) {
					if(result) 
						bootbox.alert("执行确定的方法，修改数据库中的信息",function(){});
					else
						revertFunc();
				}
			  }
			);
		},
		editable: true,
		droppable: true, // 开启拖放
		drop: function(date, event) { // 拖放完成后触发
			
			// retrieve the dropped element's stored Event Object
			var originalEventObject = $(this).data('eventObject');
			var $extraEventClass = $(this).attr('data-class');
			
			// we need to copy it, so that multiple events don't have a reference to the same object
			var copiedEventObject = $.extend({}, originalEventObject);
			
			// assign it the date that was reported
			copiedEventObject.start = date;
			copiedEventObject.allDay = true;//设为true后，默认为全天的时间，可以通过左右拉伸来实现跨天数
			if($extraEventClass) 
				copiedEventObject['className'] = [$extraEventClass];
			
//			console.log(copiedEventObject);
			
			// render the event on the calendar
			// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
			$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
			
			// 拖动之后移除？
			if ($('#drop-remove').is(':checked')) {
				// if so, remove the element from the "Draggable Events" list
				$(this).remove();
			}
			
		},
		selectable: true,
		selectHelper: true,
		select: function(start, end, allDay) {
			bootbox.setDefaults("locale","zh_CN");//设置语言为中文
			bootbox.prompt("备忘录:", function(title) {
				if (title !== null) {
					calendar.fullCalendar('renderEvent', 
						{
							title: title,
							start: start,
							end: end,
							allDay: allDay,
							className: 'label-info'
						},
						true // make the event "stick"
					);
				}
			});

			calendar.fullCalendar('unselect');
		},
		eventClick: function(calEvent, jsEvent, view) {
			console.log(jsEvent);
			console.log(calEvent);
			console.log(view);

			//display a modal
			/* var modal = 
			'<div class="modal fade">\
			  <div class="modal-dialog">\
			   <div class="modal-content">\
				 <div class="modal-body">\
				   <button type="button" class="close" data-dismiss="modal" style="margin-top:-10px;">&times;</button>\
				   <form class="no-margin">\
					  <label>备忘录</label>\
					  <input class="middle" autocomplete="off" type="text" value="' + calEvent.title + '" />\
					 <button type="submit" class="btn btn-sm btn-success"><i class="ace-icon fa fa-check"></i> 保存</button>\
				   </form>\
				 </div>\
				 <div class="modal-footer">\
					<button type="button" class="btn btn-sm btn-danger" data-action="delete"><i class="ace-icon fa fa-trash-o"></i> 删除</button>\
					<button type="button" class="btn btn-sm" data-dismiss="modal"><i class="ace-icon fa fa-times"></i> 取消</button>\
				 </div>\
			  </div>\
			 </div>\
			</div>'; */
			
			//为了让编辑框显示的大一点，做此修改
			/* <input class="bootbox-input bootbox-input-text form-control" autocomplete="off" type="text"> */

			var modal = '<div class="modal fade">\
						  <div class="modal-dialog">\
						   <div class="modal-content">\
							   <form class="no-margin">\
								 <div class="modal-body">\
								   <button type="button" class="close" data-dismiss="modal" style="margin-top:-10px;">&times;</button>\
									  <label>备忘录</label>\
									  <input class="bootbox-input bootbox-input-text form-control" autocomplete="off" type="text" value="' + calEvent.title + '" />\
								 </div>\
								 <div class="modal-footer">\
										<button type="submit" class="btn btn-sm btn-success"><i class="ace-icon fa fa-check"></i> 保存</button>\
										<button type="button" class="btn btn-sm btn-danger" data-action="delete"><i class="ace-icon fa fa-trash-o"></i> 删除</button>\
										<button type="button" class="btn btn-sm" data-dismiss="modal"><i class="ace-icon fa fa-times"></i> 取消</button>\
								 </div>\
							   </form>\
						  </div>\
						 </div>\
						</div>';

			var modal = $(modal).appendTo('body');
			modal.find('form').on('submit',function(ev) {
				ev.preventDefault();
				console.log('calEvent.start: ' + calEvent.start.format('YYYY-MM-DD HH:mm:ss'));
				if(calEvent.end)
					console.log('calEvent.end: ' + calEvent.end.format('YYYY-MM-DD HH:mm:ss'));
				calEvent.title = $(this).find("input[type=text]").val();
				calendar.fullCalendar('updateEvent',calEvent);
				modal.modal("hide");
			});
			modal.find('button[data-action=delete]').on('click', function() {
				calendar.fullCalendar('removeEvents', function(ev) {
					return (ev._id == calEvent._id);
				})
				modal.modal("hide");
			});

			modal.modal('show').on('hidden', function() {
				modal.remove();
			});

		}

	});

})
